package com.yn.bsc.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yn.bsc.core.AbstractService;
import com.yn.bsc.dao.MenuMapper;
import com.yn.bsc.model.Menu;
import com.yn.bsc.model.UserInfo;
import com.yn.bsc.service.MenuService;
import com.yn.bsc.vo.MenuBean;

/**
 * Created by ZuoLG on 2017/09/18.
 */
@Service
@Transactional
public class MenuServiceImpl extends AbstractService<Menu> implements MenuService {
	@Resource
	private MenuMapper menuMapper;

	@Override
	public List<MenuBean> selectUserMenuAll(UserInfo userInfo) {

		List<Menu> list = menuMapper.selectUserMenuAll(userInfo);
		List<MenuBean> menus = getMenu(list);
		return menus;
	}

	/**
	 * 获取当前用户的菜单，如果有三级菜单需重写 @return List<MenuBean> @throws
	 */
	private List<MenuBean> getMenu(List<Menu> list) {
		List<MenuBean> menus = new ArrayList<>();
		MenuBean mb = null;
		MenuBean childmb = null;
		if (list == null) {
			return null;
		}
		for (Menu menu : list) {
			if (menu.getMenuParentId() == null || menu.getMenuParentId() == 0) {
				mb = new MenuBean();
				BeanUtils.copyProperties(menu, mb);
				menus.add(mb);
				for (Menu childMenu : list) {
					if (childMenu.getMenuParentId() != null && childMenu.getMenuParentId() == menu.getId()) {
						childmb = new MenuBean();
						BeanUtils.copyProperties(childMenu, childmb);
						if (mb.getChildMenu() == null) {
							mb.setChildMenu(new ArrayList<>());
						}
						mb.getChildMenu().add(childmb);
					}

				}

			}
		}
		return menus;
	}

}
